<template>
  <div class="orders-container">
    <!-- 订单标签页 -->
    <div class="order-tabs">
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待支付订单" name="pending"></el-tab-pane>
        <el-tab-pane label="已完成订单" name="completed"></el-tab-pane>
        <el-tab-pane label="已取消订单" name="canceled"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <el-empty v-if="!loading && orders.length === 0" description="暂无订单" />
      <div class="order-item" v-for="order in filteredOrders" :key="order.id" v-loading="loading">
        <el-card class="order-card" shadow="hover" :class="`status-${order.status}`">
          <div class="order-header">
            <span class="order-id">订单号: {{ order.id }}</span>
            <div class="order-status-tag" :class="`status-${order.status}`">
              {{ getStatusText(order.status) }}
            </div>
            <span class="create-time">下单时间: {{ order.createTime }}</span>
          </div>
          <div class="order-content">
            <div class="product-name">{{ order.information }}</div>
            <div class="order-price">¥{{ order.expend }}</div>
          </div>
          <div class="order-footer">
            <template v-if="order.status === 0">
              <el-button type="primary" size="small" round @click="showPaymentDialog(order)">
                立即支付
              </el-button>
            </template>
            <template v-else-if="order.status === 1">
              <span class="status-text" data-status="1">制作中</span>
            </template>
            <template v-else-if="order.status === 2">
              <span class="status-text" data-status="2">已取消</span>
            </template>
            <template v-else-if="order.status === 3">
              <span class="status-text" data-status="3">已完成</span>
            </template>
            <template v-else>
              <el-button type="primary" size="small" round>查看详情</el-button>
            </template>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <el-dialog v-model="paymentVisible" title="订单支付" width="380px" custom-class="compact-dialog" :before-close="handleClose">
      <div class="payment-content">
        <h3 class="payment-title">订单信息</h3>
        <div class="payment-detail">
          <div class="detail-row">
            <span class="detail-label">订单号:</span>
            <span class="detail-value">{{ currentOrder.id }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">金额:</span>
            <span class="detail-value price">¥{{ currentOrder.expend }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">商品:</span>
            <span class="detail-value">{{ currentOrder.information }}</span>
          </div>

          <!-- 优惠券选择 -->
          <div class="detail-row">
            <span class="detail-label">优惠券:</span>
            <el-select v-model="selectedCoupon" placeholder="请选择优惠券" style="width: 100%">
              <el-option
                v-for="coupon in availableCoupons"
                :key="coupon.id"
                :label="`${coupon.name}`"
                :value="coupon"
                :disabled="coupon.isExpired || coupon.used"
              >
                <span style="float: left">{{ coupon.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px">
                  {{ coupon.isExpired ? '已过期' : coupon.used ? '已使用' : '可用' }}
                </span>
              </el-option>
            </el-select>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="handleCancelOrder">取消订单</el-button>
          <el-button type="primary" size="small" @click="handlePay">立即支付</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <BottomNav />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import BottomNav from '@/components/BottomNav.vue'
import {
  getAll,
  getNoPaid,
  getProcessed,
  getCanceled,
  pay,
  cancelPay
} from '@/api/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyCoupon } from '@/api/me'

// 响应式状态
const activeTab = ref('all')
const orders = ref([])
const loading = ref(false)
const paymentVisible = ref(false)
const coupons = ref([])
const selectedCoupon = ref(null)
const currentOrder = ref({})  
const serverIp = '8.156.75.38'; // 硬编码测试
const pre = ref(`ws://${serverIp}:8080/websocket`)

// 获取订单数据
watch(activeTab, async (newVal) => {
  try {
    loading.value = true
    let res
    switch (newVal) {
      case 'pending':
        res = await getNoPaid()
        break
      case 'completed':
        res = await getProcessed()
        break
      case 'canceled':
        res = await getCanceled()
        break
      default:
        res = await getAll()
    }

    if (res.code === 1) {
      orders.value = res.data.map(order => ({
        ...order,
        createTime: formatDate(order.createTime)
      }))
    }
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loading.value = false
  }
})

onMounted(async () => {
  try {
    loading.value = true
    const res = await getAll()
    if (res.code === 1) {
      orders.value = res.data.map(order => ({
        ...order,
        createTime: formatDate(order.createTime)
      }))
    }
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loading.value = false
  }
})

// 显示支付弹窗并加载优惠券
function showPaymentDialog(order) {
  currentOrder.value = { ...order }
  paymentVisible.value = true
  // fetchCoupons()
}
// 获取优惠券
async function fetchCoupons() {
  try {
    const res = await getMyCoupon()
    if (res.code === 1) {
      coupons.value = res.data.map(c => ({
        id: c.id,
        name: c.name,
        value: c.value,
        minAmount: c.minAmount,
        startTime: c.startTime,
        endTime: c.endTime,
        isExpired: new Date(c.endTime) < new Date(),
        used: false, // 假设未使用，如果后端有字段可替换
        uid: c.uid // ✅ 添加这个字段
      }))
    }
  } catch (error) {
    ElMessage.error('获取优惠券失败')
    console.error('获取优惠券失败:', error)
  }
}

async function handlePay() {
  try {
    const res = await pay({
      id: currentOrder.value.id,
      expend: currentOrder.value.expend,
      couponId: selectedCoupon.value?.id || null,
      uid: selectedCoupon.value?.uid || null // ✅ 新增字段
    });

    if (res.code === 1) {
      ElMessage.success('支付成功');

      // 建立 WebSocket 连接并发送消息
      const ws = new WebSocket(pre.value + '/' + currentOrder.value.id);

      ws.addEventListener('open', () => {
        console.log('WebSocket 连接已打开');
        const message = JSON.stringify({
          orderId: currentOrder.value.id,
          action: 'pay'
        });
        ws.send(message);
      });

      ws.addEventListener('message', (event) => {
        console.log('收到后端响应:', event.data);
        ws.close();
      });

      paymentVisible.value = false;

      // 刷新订单列表
      const fetchMethod = activeTab.value === 'pending' ? getNoPaid : getAll;
      const refreshRes = await fetchMethod();
      orders.value = refreshRes.data.map(order => ({
        ...order,
        createTime: formatDate(order.createTime)
      }));
    } else {
      ElMessage.error(res.msg || '支付失败');
    }
  } catch (error) {
    ElMessage.error('支付失败: ' + error.message);
  }
}

// 取消订单
async function handleCancelOrder() {
  try {
    const res = await cancelPay(currentOrder.value.id)
    if (res.code === 1) {
      ElMessage.success('订单已取消')
      paymentVisible.value = false
      const refreshRes = await getAll()
      orders.value = refreshRes.data.map(order => ({
        ...order,
        createTime: formatDate(order.createTime)
      }))
    } else {
      ElMessage.error(res.msg || '取消失败')
    }
  } catch (error) {
    ElMessage.error('取消订单失败: ' + error.message)
  }
}

// 弹窗关闭确认
function handleClose(done) {
  ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done()
  }).catch(() => {})
}

// 工具函数
function formatDate(timestamp) {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

function padZero(num) {
  return num < 10 ? `0${num}` : num
}

function getStatusText(status) {
  const statusMap = {
    0: '待支付',
    1: '制作中',
    2: '已取消',
    3: '已完成'
  }
  return statusMap[status] || ''
}

// 仅显示可用优惠券
const availableCoupons = computed(() => {
  return coupons.value.filter(coupon => 
    !coupon.isExpired && 
    !coupon.used &&
    coupon.minAmount <= currentOrder.value.expend
  )
})

const filteredOrders = computed(() => {
  return orders.value.map(order => ({
    ...order,
    createTime: formatDate(order.createTime),
  }))
})
</script>

<style scoped>
.orders-container {
  padding-bottom: 60px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.order-tabs {
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: center;
}

.custom-tabs {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 16px;
  border-radius: 8px;
  background-color: #ffffff;
  display: flex;
  justify-content: space-between;
}

.custom-tabs :deep(.el-tabs__nav) {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.custom-tabs :deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding: 12px 0;
  border-radius: 8px;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  background-color: #5c6bc0;
  color: #ffffff;
}

.order-list {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
}

.order-item {
  transition: transform 0.3s ease;
}

.order-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  background-color: #ffffff;
  border-left: 6px solid transparent;
}

.order-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

/* 状态边框色 */
.order-card.status-0 {
  border-color: #ffa726;
}
.order-card.status-1 {
  border-color: #42a5f5;
}
.order-card.status-2 {
  border-color: #e0e0e0;
}
.order-card.status-3 {
  border-color: #66bb6a;
}

/* 订单头部 */
.order-header {
  display: flex;
  gap: 8px;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px 8px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #eee;
}

.order-id {
  font-weight: bold;
  color: #333;
}

.create-time {
  font-size: 12px;
  color: #999;
}

/* 状态标签 */
.order-status-tag {
  display: inline-block;
  width: fit-content;
  padding: 4px 12px;
  font-size: 12px;
  font-weight: 600;
  border-radius: 20px;
  align-self: flex-start;
}

.order-status-tag.status-0 {
  color: #ef6c00;
  background-color: #fff3e0;
}
.order-status-tag.status-1 {
  color: #1e88e5;
  background-color: #e3f2fd;
}
.order-status-tag.status-2 {
  color: #666;
  background-color: #f5f5f5;
}
.order-status-tag.status-3 {
  color: #2e7d32;
  background-color: #e8f5e9;
}

/* 商品信息 */
.order-content {
  padding: 16px;
}

.product-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 6px;
}

.order-price {
  font-size: 20px;
  font-weight: bold;
  color: #ef5350;
}

/* 按钮区域 */
.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 8px 16px 16px;
}

.status-text {
  padding: 4px 12px;
  font-size: 14px;
  border-radius: 20px;
  margin-right: 10px;
}

.status-text[data-status="1"] {
  color: #fb8c00;
  background-color: #fff3e0;
}
.status-text[data-status="2"] {
  color: #9e9e9e;
  background-color: #f5f5f5;
}
.status-text[data-status="3"] {
  color: #43a047;
  background-color: #e8f5e9;
}

/* 支付按钮 */
.el-button--primary {
  background-color: #ff7043;
  border-color: #ff7043;
}
.el-button--primary:hover {
  background-color: #fb8c00;
  border-color: #fb8c00;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 0;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.bottom-nav .el-col {
  text-align: center;
  cursor: pointer;
  font-size: 12px;
  color: #666;
  transition: color 0.2s ease;
}

.bottom-nav .el-col.active,
.bottom-nav .el-icon.active {
  color: #ff7043;
}
</style>